package com.pattern.behavioural;

/**
 * @author Ping
 * @date 2022/5/9 14:51
 **/
public class ResponsiblityDemo {
    public static void main(String args[]) {
        // build responsiblity chain
        Teacher teacher = new Teacher() ;
        Director director = new Director() ;
        Dean dean = new Dean() ;
        teacher.setSuccessor(director) ;
        director.setSuccessor(dean);
        // client propose the req
        LeaveRequest zhangsanReq = new LeaveRequest("zhangsan", 1) ;
        LeaveRequest lisiReq = new LeaveRequest("lisi", 28) ;

        teacher.process(zhangsanReq);
        teacher.process(lisiReq);
    }
}

class LeaveRequest {
    public static final Boolean AGREE = true ;
    public static final Boolean DIS_AGREE = false ;
    private String name ;
    private int days ;
    private boolean result ;

    public LeaveRequest(String name, int days) {
        this.name = name;
        this.days = days;
        this.result = false ;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    public int getDays() {
        return days;
    }
}

interface RequestHandler {
    public RequestHandler setSuccessor(RequestHandler successor) ;
    public void process(LeaveRequest req) ;
}
abstract class AbstractHandler implements RequestHandler {
    protected RequestHandler successor ;

    @Override
    public RequestHandler setSuccessor(RequestHandler successor) {
        this.successor = successor ;
        return this ;
    }
}
class Teacher extends AbstractHandler {
    @Override
    public void process(LeaveRequest req) {
        System.out.println("[INFO] the request was processed by TEACHER.") ;
        if (req.getDays() <= 1) {
            req.setResult(LeaveRequest.AGREE);
            System.out.println("[INFO] the request was APPROVED by TEACHER.") ;
            return ;
        }
        this.successor.process(req);
    }
}

class Director extends AbstractHandler {
    @Override
    public void process(LeaveRequest req) {
        System.out.println("[INFO] the request was processed by DIRECTOR.") ;
        if (req.getDays() <= 7) {
            req.setResult(LeaveRequest.AGREE);
            System.out.println("[INFO] the request was APPROVED by DIRECTOR.") ;
            return ;
        }
        this.successor.process(req);
    }
}
class Dean extends AbstractHandler {
    @Override
    public void process(LeaveRequest req) {
        System.out.println("[INFO] the request was processed by DEAN.") ;
        if (req.getDays() <= 30) {
            req.setResult(LeaveRequest.AGREE);
            System.out.println("[INFO] the request was APPROVED by DEAN.") ;
            return ;
        }
        this.successor.process(req);
    }
}

